/*
   Copyright (C) 2010- Peter Bui and Aaron Dingler.
   This software is distributed under the GNU General Public License.
   See the file COPYING for details.
 */

#include "smq_common.h"
#include "smq_catalog.h"
#include "smq_client.h"

#include <debug.h>
#include <link.h>

#include <string.h>
#include <stdlib.h>
#include <time.h>

static int SMQ_Create_RPC_Timeout     = SMQ_CLIENT_DEFAULT_RPC_TIMEOUT;
static int SMQ_Create_Connect_Timeout = SMQ_CLIENT_DEFAULT_CONNECT_TIMEOUT;
static int SMQ_Create_Connect_Mode    = SMQ_CLIENT_CONNECT_FCFS;

static void
smq_create_show_help(const char *progname)
{
    printf("usage: %s [options] [host:]queue_name\n", progname);
    printf("Options:\n");
    printf(" -d <flag>   Enable debugging for this subsystem.\n");
    printf(" -t <time>   RPC timeout (default is %ds).\n", SMQ_Create_RPC_Timeout);
    printf(" -r          Select random host (default is FCFS).\n");
    printf(" -h          This message.\n");
}

static void
smq_create_parse_command_line_arguments(int argc, char *argv[])
{
    int	c;

    while ((c = getopt(argc, argv, "d:t:rh")) != -1) {
        switch (c) {
            case 'd': 
                debug_flags_set(optarg); 
                break;
            case 't': 
                SMQ_Create_RPC_Timeout = atoi(optarg);
                break;
	    case 'r':
		SMQ_Create_Connect_Mode = SMQ_CLIENT_CONNECT_RANDOM;
		srand(time(0));
		break;
            case 'h':
                smq_create_show_help(argv[0]); 
                exit(EXIT_SUCCESS);
                break;
            default:
                smq_create_show_help(argv[0]); 
                exit(EXIT_FAILURE);
                break;
        }
    }
}

int
main(int argc, char *argv[])
{
    struct link *manager_link;
    char target[SMQ_LINE_MAX];
    int result;

    smq_create_parse_command_line_arguments(argc, argv);

    if((argc - optind) != 1) {
        smq_create_show_help("smq_create");
        exit(EXIT_FAILURE);
    }

    strncpy(target, argv[optind], SMQ_LINE_MAX);

    manager_link = smq_client_connect(target, 0, SMQ_Create_Connect_Mode, SMQ_Create_Connect_Timeout);
    if (!manager_link)
	fatal("could not connect to queue: %s", target);

    result = smq_client_create(manager_link, target, SMQ_Create_RPC_Timeout);
    if (!result)
	fatal("create RPC failed: %d", result);

    return EXIT_SUCCESS;
}

/* 
vim: sw=4 sts=4 ts=8 ft=cpp
*/
